package top.v5it.logback.push.channel.mail;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import top.v5it.logback.push.channel.ChannelPushStrategy;
import top.v5it.logback.push.channel.LogInfo;
import top.v5it.logback.push.channel.VoidFunc;
import top.v5it.logback.push.util.StringTemplateUtil;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * 邮件推送消息
 *
 * @author zhanpu
 * @date 2022/9/7
 */
public class MailChannelPushStrategy implements ChannelPushStrategy {

    private final static Executor executor = ThreadUtil.newSingleExecutor();

    @Override
    public <E> boolean push(Map<String, Object> pushConfig, byte[] payload, VoidFunc failedCallback) {
        final LogInfo logInfo = getLogInfo(payload);
        // 拼装at联系人
        final String contactsStr = MapUtil.getStr(pushConfig, "contacts");
        final List<String> contacts = StrUtil.splitTrim(contactsStr, ",");
        final String content = StringTemplateUtil.mail(logInfo.getLevel(), logInfo.getLogger(), logInfo.getMessage().getDescription());
        // 异步发送
        CompletableFuture.runAsync(() -> MailUtil.sendText(contacts, logInfo.getMessage().getTitle(), content), executor)
                .exceptionally(e -> {
                    if (Objects.nonNull(e)) failedCallback.call();
                    return null;
                });
        return true;
    }
}
